package com.opennews.openplatform.controller;

import com.opennews.openplatform.dto.CheckPermissionDto;
import com.opennews.openplatform.util.SharedUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

@RequiredArgsConstructor
@Component
public class AuthInterceptor implements HandlerInterceptor {
    private final RestTemplate restTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String resourceUri = request.getRequestURI();
        String authorizationHeader = request.getHeader("authorization");

        CheckPermissionDto checkPermissionDto = new CheckPermissionDto();
        checkPermissionDto.setResourceUri(resourceUri);
        checkPermissionDto.setAuthorizationHeader(authorizationHeader);
        checkPermissionDto.setHttpMethod(request.getMethod());

        Boolean isAuthorized = false;

        try {
            isAuthorized = restTemplate.postForObject("lb://auth-service/api/auth/permissions/check", checkPermissionDto, Boolean.class);
        } catch (Exception e) {
            isAuthorized = false;
        } finally {
            if (Boolean.FALSE.equals(isAuthorized)) {
                SharedUtil.sendErrorResponse(response, HttpStatus.UNAUTHORIZED.value(), "UNAUTHORIZED", "ERROR_USER_ACCOUNT_NOT_AUTHORIZED", request.getRequestURI().trim());
            }

            return Boolean.TRUE.equals(isAuthorized);
        }
    }
}